package com.tian;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.time.LocalDateTime;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-02-28 11:07
 * {@code @version:} 1.0
 */
@Slf4j
public class LogSender {
    private final RabbitTemplate rabbitTemplate;
    private final String exchange;
    private final String routingKey;
    private final boolean enabled;

    public LogSender(RabbitTemplate rabbitTemplate,
                     String exchange,
                     String routingKey,
                     boolean enabled) {
        this.rabbitTemplate = rabbitTemplate;
        this.exchange = exchange;
        this.routingKey = routingKey;
        this.enabled = enabled;
    }

    public void sendLog(String businessType, String level, String content) {
        LogMessage message = new LogMessage();
        message.setBusinessType(businessType);
        message.setLevel(level);
        message.setContent(content);
        message.setTimestamp(LocalDateTime.now());
        message.setThreadName(Thread.currentThread().getName());
        String jsonString = JSON.toJSONString(message);
        // 判断是否启用日志记录
        if (!enabled) {
            log.info("Log sending is disabled");
            return;
        }
        try {
            log.info("Sending log message: {}", jsonString);
            rabbitTemplate.convertAndSend(exchange, routingKey, jsonString);
        } catch (Exception e) {
            log.error("Failed to send log message", e);
        }
    }
}
